package com.qf.spring2202.customfactory.utils;

import com.qf.spring2202.customfactory.service.UserService;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class MyFactory {
    private String configFilePath;
    //该实例属性用于保存解析后配置文件内容
    private Properties properties=new Properties();

    private Map<String,Object> cache=new HashMap<>();


    /*
    * 如果不传配置文件名，默认配置文件名为beans.properties
    * */
    public MyFactory() throws IOException {
        this("/beans.properties");
    }


    public MyFactory(String configFilePath) throws IOException {
        this.configFilePath=configFilePath;

        //配置文件------》InputStream
        InputStream inputStream = getClass().getResourceAsStream(configFilePath);

        //把输入流中的内容转换成properties对象中的信息
        properties.load(inputStream);
    }

    /*
    * beanName 对象的标识符
    * 返回一个可用的对象
    * */
    public Object getBean(String beanName) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        //先检查工程的缓存中是否有
        Object obj = cache.get(beanName);

        if (obj!=null){
            return obj;
        }
        //1.根据beanName 获取所需的bean的类的全限命名
        String clazzname = properties.getProperty(beanName);
        //2.根据类的全限命名创建对象
        obj=createObject(clazzname);
        if(obj!=null){
            cache.put(beanName,obj);
        }
        return obj;
    }

    private Object createObject(String clazzname) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> clazz = Class.forName(clazzname);
        //反射创建对象
        Object o = clazz.newInstance();
        return o;
    }

    public static void main(String[] args) throws IOException, IllegalAccessException, ClassNotFoundException, InstantiationException {
        MyFactory myFactory = new MyFactory();
        UserService userService = (UserService) myFactory.getBean("UserService");
        System.out.println(userService.getUser(200));
    }
}
